package com.wxy.gxs.springbootprojectday25.service.serviceImpl;

import com.wxy.gxs.springbootprojectday25.Mapper.TypeRespository;
import com.wxy.gxs.springbootprojectday25.bean.Type;
import com.wxy.gxs.springbootprojectday25.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class TypeServiceImpl implements TypeService {
    @Autowired
    private TypeRespository typeRespository;


    @Override
    public List<Type> findAll() {
        List<Type> types = typeRespository.findAll();
        return types;
    }

//    注意事项:

    /**
     * 使用spring data jpa的时候分页返回的数据类型是 Page<list>
     * @param pageable
     * @return
     */

    @Override
    public  Page<Type> listType(Pageable pageable) {
        Page<Type> types = typeRespository.findAll(pageable);
        return types;
    }

    @Override
    public Type findTypeById(Long id) {
        Type type = typeRespository.findOne(id);
        return type;
    }

    @Override
    public Type findTypeByName(String name) {
        Type type = typeRespository.findByName(name);
        return type;
    }

    @Override
    public Type add(Type type) {
        Type type1 = typeRespository.save(type);
        return type1;
    }

    @Override
    public  void delete(Long id) {
        /**
         * 接触结果:
         *  1.删除没有返回的数据
         */
        typeRespository.delete(id);

    }

    /**
     * 需要注意的事项:
     *      1.使用  spring data jpa 的时候,操作的具体思路:
     *          通过编号查询出来实体类
     *          通过beanUtils.copyProperties(type,one),也就是将前面的参数内容复制给后面查询查询
     *          实体类
     * @param id
     * @param type
     * @return
     */

    @Override
    public Type update(Long id, Type type) {
        Type one = typeRespository.findOne(id);
        if(one !=null){
            return type;
        }
        BeanUtils.copyProperties(type,one);
        Type save = typeRespository.save(one);
        return save;
    }
}
